const express = require('express');
const axios = require('axios');
const router = express.Router();
const pool = require('../db');

// 轮播
router.post('/banner/page', async (req, res) => {
	try {
		console.log('我进入了page', req.body.page)
    const { page, limit } = req.body;
    console.log('page and limit', page, limit)
    if (!page || !limit) {
      return res.status(500).json({ message: '请填写page和limit参数' });
    }
    // 计算跳过的记录数
    const offset = (page - 1) * limit;

    // 构建查询语句
    const query = 'SELECT * FROM banner WHERE isShow = 1 LIMIT ?, ?';
    const values = [offset, limit];
    // 执行查询
    pool.query(query, values, (error, results) => {
      console.log('results', results)
      if (error) {
        return res.status(500).json({ message: error.message });
      }

      // 获取总记录数
      pool.query('SELECT COUNT(*) AS count FROM banner WHERE isShow = 1', (err, countResult) => {
        console.log('results=count', results)
        if (err) {
          return res.status(500).json({ message: err.message });
        }

        const totalRecords = countResult[0].count;
        const totalPages = Math.ceil(totalRecords / limit);

        // 构建响应数据
        const response = {
          success: true,
          code: 200,
          data: {
            page: page,
            limit: limit,
            total: totalRecords,
            totalPages: totalPages,
            records: results
          },
          errMsg: '成功'
        };

        // 返回响应
        res.json(response);
      });
    });
	} catch (error) {
		res.status(500).send()
	}
});

module.exports = router;